<?php

namespace app\backstage\controller;

use think\Controller;
use think\Request;
use app\backstage\model\RentHouse as RentModel;
use app\api\model\Index as apiModel;
use Db;
class RentHouse extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request, RentModel $rentModel)
    {
        if($request->isAjax()){

            //分页
            $pageSize = 10;
            $params = $request->param();

            $page = $params['page']?:1;
            $offset = ($page-1)*$pageSize;

            $where = [];
            //搜索
            if(!empty($params['start'])){
                $where[] = ['a.create_time','>=',strtotime($params['start'])];
            }

            if(!empty($params['end'])){
                $where[] = ['a.create_time','<=',strtotime($params['end'])];
            }

            if(!empty($params['seach_text'])){
                $where[] = ['a.title','like',"%{$params['seach_text']}%"];
            }

            //楼盘列表
            $data = $rentModel->field('a.title,a.charter_money,a.total_area,a.create_time,a.id,a.thumb_img,b.name area_name')
                ->alias('a')->join('region b','a.area_id=b.id','left')
                ->where($where)->order('a.id','desc')->limit($offset,$pageSize)->select();

            if($data){
                foreach($data as &$v){
                    $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
                    $v['thumb_img'] = config('api.oss_img_path').$v['thumb_img'];

                }
            }


            if(!empty($where)){
                $count = $rentModel->where($where)->count();
            }else{
                $count = $rentModel->count();
            }

            $pageData = ['count'=>$count,'page'=>$page,'pageSize'=>$pageSize];

            return ['code'=>200,'listData'=>$data,'pageData'=>$pageData];

        }
        return view('index');
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create(Request $request)
    {
        $rentout_id = $request->get('rentout_id');

        if($rentout_id){

            $rentout = Db::name('app_user_rentout')->where('id',$rentout_id)->find();
        }

        if(empty($rentout)){
            $rentout=array(
                'uptown'=>'',
                'address'=>'',
                'charter_money'=>'',
                'id'=>0
            );
        }
        $broker = Db::name('house_broker')->field('id,broker_name')->select();
        $labels = Db::name('house_label')->field('id,tag_name')->where('type',3)->select();
        $res = array(
            'aspect'=>config('api.aspect'),
            'carport_types'=>config('api.carport_types'),
            'purpose'=>config('api.purpose'),
            'heating'=>config('api.heating'),
            'property_right_types'=>config('api.property_right_types'),
            'transaction_types'=>config('api.transaction_types'),
            'fitment_case'=>config('api.fitment_case'),
            'allocations' =>config('api.allocations'),
            'brokers'=>$broker,
            'labels' =>$labels,
            'rentout' =>$rentout
        );
        return view('create',$res);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        if($request->isAjax()){

            $data = $request->post();
            $lat = $data['lat'];
            $lng = $data['lng'];

            //片区adcode
//            $sql = 'select id,name from region where pid='.$data['area_id'].' and  lat > '.$lat.' and lat < '.$lat.' and lng > '.$lon.' and lng < '.$lon.' order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lon.'* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc limit 1';
//            $region = Db::query($sql);

            $region = [];
            $flag =[];

            $regions = Db::name('region')->field('id,name,lng,lat')->where('pid',$data['area_id'])->select();

//            dump($regions);
            if($regions){

                foreach ($regions as $k=>$v){

                    $r = apiModel::calcDistance($lat,$lng,$v['lat'],$v['lng']);
                   $region["$r"] = $v['id'];
                   $flag[$v['id']] = $r;

                }

                asort($flag);
//                $first_val = reset($flag);

                $first_key = key($flag);

                $data['area_id'] = $first_key;

            }else{
                return ['code'=>101,'msg'=>'无法获取位置'];

            }



            if(!empty($data['labels'])){
                $data['labels'] = join(',',$data['labels']);
            }

            if(!empty($data['allocation'])){
                $data['allocation'] = join(',',$data['allocation']);
            }

            $data['rent_way'] = '押'.$data['rent_way1'].'付'.$data['rent_way2'];

            unset( $data['rent_way1']);
            unset( $data['rent_way2']);


//            $data['module_id'] = 2;


            $data['viewpager'] = json_encode($data['viewpager']);
//            dump($data);die;
            $data['create_time'] = time();

            $data['coding'] = 'R'.time();

            Db::startTrans();

            $model = new RentModel($data);

            $res = $model->allowField(true)->save();

            if($res){

                if(!empty($data['rentout_id'])){
                    $updSell = Db::name('app_user_rentout')->where('id',$data['rentout_id'])->update(['house_id'=>$model->id,'off'=>1]);

                    if($updSell){
                        Db::commit();
                        return ['code'=>200];
                    }else{
                        Db::rollback();
                        return ['code'=>101,'msg'=>'关联用户出租房源失败'];

                    }
                }

                Db::commit();


                return ['code'=>200,'res'=>$res];
            }else{
                return ['code'=>101,'msg'=>'插入失败'];
            }

        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $info = RentModel::where('id',$id)->find();

        $broker = Db::name('house_broker')->field('id,broker_name')->select();
        $labels = Db::name('house_label')->field('id,tag_name')->where('type',3)->select();

        $info['rent_way'] = array(
           mb_substr($info['rent_way'],1,1),  mb_substr($info['rent_way'],3,1)
        );



        $info['labels'] = explode(',',$info['labels']);


        $cpz = config('api.allocations');

        $pz = explode(',',$info['allocation']);

        $pzIndex = [];
        foreach($pz as $k =>$v) {
            if (!$flag = in_array($v, $cpz)) {
                array_push($cpz, $v);
            }else{

                $pzIndex[]=array_search($v,$cpz);
            }
        }


        $res = array(
            'aspect'=>config('api.aspect'),
            'carport_types'=>config('api.carport_types'),
            'purpose'=>config('api.purpose'),
            'heating'=>config('api.heating'),
            'property_right_types'=>config('api.property_right_types'),
            'transaction_types'=>config('api.transaction_types'),
            'fitment_case'=>config('api.fitment_case'),
            'allocations' =>$cpz,
            'brokers'=>$broker,
            'labels' =>$labels,
            'details'=>$info,
            'pzIndex'=>$pzIndex
        );


        return view('edit',$res);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if($request->isAjax()){

            $data = $request->post();
            $lat = $data['lat'];
            $lng = $data['lng'];

            //片区adcode
//            $sql = 'select id,name from region where pid='.$data['area_id'].' and  lat > '.$lat.' and lat < '.$lat.' and lng > '.$lon.' and lng < '.$lon.' order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lon.'* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc limit 1';
//            $region = Db::query($sql);

            $region = [];
            $flag =[];

            $regions = Db::name('region')->field('id,name,lng,lat')->where('pid',$data['area_id'])->select();

//            dump($regions);
            if($regions){

                foreach ($regions as $k=>$v){

                    $r = apiModel::calcDistance($lat,$lng,$v['lat'],$v['lng']);
                    $region["$r"] = $v['id'];
                    $flag[$v['id']] = $r;

                }

                asort($flag);
//                $first_val = reset($flag);

                $first_key = key($flag);

                $data['area_id'] = $first_key;

            }else{
                return ['code'=>101,'msg'=>'无法获取位置'];

            }



            if(!empty($data['labels'])){
                $data['labels'] = join(',',$data['labels']);
            }

            if(!empty($data['allocation'])){
                $data['allocation'] = join(',',$data['allocation']);
            }

            $data['rent_way'] = '押'.$data['rent_way1'].'付'.$data['rent_way2'];

            unset( $data['rent_way1']);
            unset( $data['rent_way2']);


//            $data['module_id'] = 2;


            $data['viewpager'] = json_encode($data['viewpager']);
//            dump($data);die;
//            $data['create_time'] = time();

//            dump($data);die;

            $model = new RentModel();

            $res = $model->save($data,['id'=>$id]);

            if($res){
                return ['code'=>200,'res'=>$res];
            }else{
                return ['code'=>101,'msg'=>'修改失败'];
            }

        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $res = RentModel::destroy($id);

        if($res){
            return ['code'=>200];
        }else{
            return ['code'=>101,'msg'=>'删除失败'];
        }
    }


    /**
     * 批量删除
     *
     * @param  string  $ids
     * @return \think\Response
     */
    public function delete_all()
    {

        if($ids = request()->post('ids')){
            $res = RentModel::destroy($ids);

            if($res){
                return ['code'=>200];
            }else{
                return ['code'=>101,'msg'=>'删除失败'];
            }
        }else{
            return ['code'=>101,'msg'=>'缺少参数'];
        }

    }
}
